package com.emergency.examine.service.impl;

import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.examine.dao.PaperDao;
import com.emergency.examine.dao.PaperQuestionDao;
import com.emergency.examine.domain.Paper;
import com.emergency.examine.domain.PaperQuestion;
import com.emergency.examine.service.PaperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PaperServiceImpl implements PaperService {
    private final static Logger logger = LoggerFactory.getLogger(PaperServiceImpl.class);

    @Autowired
    private PaperDao paperDao;

    @Autowired
    private PaperQuestionDao paperQuestionDao;

    @Autowired
    private IdWorker idWorker;

    //添加试卷信息
    @Override
    public String add(Paper paper) {
        if (CommonUtils.isNullOrEmpty(paper.getId())) {
            paper.setId(idWorker.nextId());
            paper.setCreateTime(new Date());
        }
        //保存试卷信息
        paperDao.save(paper);
        questionSave(paper);
        return paper.getId().toString();
    }

    //保存题目信息
    private void questionSave(Paper paper) {
        List<PaperQuestion> paperQuestions = paper.getPaperQuestion();
        if (!CommonUtils.isNullOrEmpty(paperQuestions)) {
            paperQuestions.forEach(paperQuestion -> {
                paperQuestion.setId(idWorker.nextId());
                paperQuestion.setCreateTime(new Date());
                paperQuestion.setPaper(paper);
            });
        }
        paperQuestionDao.saveAll(paperQuestions);
    }

    //获取试卷信息
    @Override
    public Paper getInfo(Long paperId) {
        Paper paper = paperDao.findById(paperId).orElse(null);
        if (CommonUtils.isNullOrEmpty(paper)) {
            logger.info("没有这张试卷");
            return paper;
        }
        //获取题目
        paper.setPaperQuestion(paperQuestionDao.findAllByPaper(paperId));
        return paper;
    }

    //删除试卷信息
    @Override
    public void del(Long paperId) {
        paperQuestionDao.deleteByPaperId(paperId);
        paperDao.deleteById(paperId);
    }

    //查询
    @Override
    public Page<Paper> findList(Map searchMap, int page, int size) {
        Specification<Paper> specification = createSpecification(searchMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return paperDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Paper> createSpecification(Map searchMap) {

        return new Specification<Paper>() {

            @Override
            public Predicate toPredicate(Root<Paper> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 试卷备注
                if (searchMap.get("note") != null && !"".equals(searchMap.get("note"))) {
                    predicateList.add(cb.like(root.get("note").as(String.class), "%" + (String) searchMap.get("note") + "%"));
                }
                // 考试试卷
                if (searchMap.get("duration") != null && !"".equals(searchMap.get("duration"))) {
                    predicateList.add(cb.like(root.get("duration").as(String.class), "%" + (String) searchMap.get("duration") + "%"));
                }
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }
}
